import os
import jieba

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from views import textRank
from .models import ShortAnswer
from service.models import personalQB


# from unlimLattice import optimize_predict

@csrf_exempt
def showShortAnswerHomepage(request):
    return render(request, '1short.html')


@csrf_exempt
def showAllQuestion(request):
    obj = ShortAnswer.objects.all()
    return render(request, '1Stiku.html', {'mayanswer': obj})


@csrf_exempt
def show_stu_shortAnswer_answer(request):
    account = request.session.get('account')
    try:
        shortAnswer = ShortAnswer.objects.raw('SELECT * FROM `shortanswer_shortanswer` '
                                              'where shortanswer_shortanswer.ID not in'
                                              '( SELECT shortanswer_shortanswer.ID '
                                              'FROM `shortanswer_shortanswer`,`service_personalqb` '
                                              'WHERE(shortanswer_shortanswer.ID = service_personalqb.questionID '
                                              'and service_personalqb.TypeID = 3 '
                                              'and service_personalqb.Account = \'%s\') )' % format(account))

        return render(request, 'stu_shortAnswer_answer.html', {'shortAnswer': shortAnswer})
    except:
        shortAnswer is None
        return render(request, 'stu_shortAnswer_answer.html', {'shortAnswer': shortAnswer})


@csrf_exempt
def show_stu_shortAnswer_wrong(request):
    account = request.session.get('account')
    wrongShortAnswer = personalQB.objects.filter(TypeID=3, statusID=0, Account=account)
    allAnsweredShortAnswer = personalQB.objects.filter(TypeID=3, Account=account)
    return render(request, 'stu_shortAnswer_wrong.html', {'wrong': wrongShortAnswer,
                                                          'allAnsweredShortAnswer': allAnsweredShortAnswer})


@csrf_exempt
def shortAnswerQGfile(request):
    obj = request.FILES.get('file')  # 获取前端文件
    QGnum = int(request.POST.get('num'))
    f = open(os.path.join('media', obj.name), 'wb+')  # 临时写入前端文件
    for i in obj:
        f.write(i)
    f.close()
    fileName = './media/' + obj.name
    keyWords, keySentences = textRank(fileName, QGnum)  # 把输入的文本分别提取出关键词与关键句
    Dict = './static/dict.txt'
    with open(Dict, 'r', encoding='utf-8') as fileObject:  # 向关键词库导入术语
        terminology = fileObject.read().splitlines()
        for k in terminology:
            if k not in keyWords:
                keyWords.append(k)  # 自带的术语库和用户输入文本进行textrank的关键词共同组成筛选词库
    mayAnswer = []
    jieba.load_userdict(keyWords)
    for org in keySentences:
        words = jieba.lcut(org)  # 分词
        for word in words:  # 遍历分词结果
            i = 0
            if word in keyWords:  # 如果分出的词在关键词里
                if '是' in org:
                    question = org[0:org.index("是")] + '是什么？谈谈你的理解。'
                else:
                    question = "根据提取的此关键词中未生成符合条件的问题。显示原句："  # question = "根据提取的此关键词  " + word + "  中未生成符合条件的问题。显示原句："
                count = ShortAnswer.objects.count()  # 数据库个数计数
                answerObject = ShortAnswer(org=org, ID=count + 1, question=question, answer=org)  # 构建题目对象
                if not ShortAnswer.objects.filter(org=answerObject.org, question=answerObject.question):  #
                    # 如果数据库中没有此题目，不存在返回True
                    if answerObject.question[0:9] != "根据提取的此关键词":
                        mayAnswer.append(answerObject)  # 将题目对象加入到列表中
            if i > 2:
                break
    os.remove(os.path.join('media', obj.name))  # 删除缓存文件
    return render(request, '1short.html', {'mayanswer': mayAnswer})


@csrf_exempt
def saveData(request):
    res = {}
    if request.method == 'POST':
        data = request.POST.get('qg')
        init = data.split('/')  # 第一次被分割
        init = init[:-1]
        try:
            for fss in init:  # 遍历
                sss = fss.split('|')  # 切分
                org = sss[0]  # 原句
                question = sss[1]  # 问题
                answer = sss[2]  # 答案
                count = ShortAnswer.objects.count()  # 数据库个数计数
                answerObject = ShortAnswer(org=org, ID=count + 1, question=question,
                                           answer=answer)  # 构建题目对象
                if not ShortAnswer.objects.filter(org=answerObject.org,
                                                  question=answerObject.question):  # 如果数据库中没有此题目(不存在返回True)
                    answerObject.save()  # 保存到数据库
            res['status'] = 100
            return JsonResponse(res)
        except:
            res['status'] = 501
            return JsonResponse(res)
    else:
        res['status'] = 500
        return JsonResponse(res)

# def shortAnswerQGfile(request):
#     obj = request.FILES.get('file')  # 获取前端文件
#     QGnum = int(request.POST.get('num'))
#     f = open(os.path.join('media', obj.name), 'wb+')  # 临时写入前端文件
#     for i in obj:
#         f.write(i)
#     f.close()
#     mayAnswer = []
#     for i in range(0, QGnum):
#         count = ShortAnswerInfo.objects.count()  # 数据库个数计数
#         answerObject = ShortAnswerInfo(org=None, SAID=count + 1, questions=optimize_predict.result,
#                                        answer=None)  # 构建题目对象
#         if not ShortAnswerInfo.objects.filter(org=answerObject.org,
#                                               questions=answerObject.questions):  # 如果数据库中没有此题目，不存在返回True
#             answerObject.save()  # 保存到数据库
#             mayAnswer.append(optimize_predict.temp[i])  # 将题目对象加入到列表中
#     os.remove(os.path.join('media', obj.name))  # 删除缓存文件
#     return render(request, '1short.html', {'mayanswer': mayAnswer})
